# -*- coding: utf-8 -*-
__author__ = 'vladbranzei'
from pymongo import MongoClient, ASCENDING, DESCENDING
import os, sys
from pymongo.errors import DuplicateKeyError

def create(host,port, username=None, password=None):
    client = MongoClient(host, int(port))
    db = client.ulise
    if username:
        client.admin.authenticate(username, password)
    collection = db.leaderboards

    try:
        result = collection.insert({'init':'init'})
        if result:
            print('ulise.leaderboards created')

            index_name = 'game_leaderboards'
            res = collection.ensure_index([("game", DESCENDING),("name", DESCENDING),("order", DESCENDING)], unique=True, name="game_leaderboards")
            if index_name == res:
                print(index_name + " index created")
            else:
                print("an error occured while creating index " + index_name)

        else:
            print('an error occurred while creating ==leaderboards==')
    except DuplicateKeyError as e:
        print("ulise.leaderboards already exists")

    try:
        collection = db.entries
        result = collection.insert({'init':'init'})
        if result:
            print('ulise.entries created')
            index_name = "lid_eid"
            res = collection.ensure_index([("leaderboard_id", ASCENDING),("_id", ASCENDING)], unique=True, name="lid_eid")
            if index_name == res:
                print(index_name + " index created")
            else:
                print("an error occurred while creating index " + index_name)

            index_name = "owner"
            res = collection.ensure_index([("owner", ASCENDING)], unique=True, name="owner")
            if index_name == res:
                print(index_name + " index created")
            else:
                print("an error occurred while creating index " + index_name)
        else:
            print('an error occured while creating ==entries==')
    except:
        print("ulise.entires already exists")


if __name__ == "__main__":
    if len(sys.argv) == 3:
        host = sys.argv[1].split('=')[1]
        port = sys.argv[2].split('=')[1]
        print("host = " + host)
        print("port = " + port)
        create(host,port)
    else:
        host = os.environ['OPENSHIFT_MONGODB_DB_HOST']
        port = os.environ['OPENSHIFT_MONGODB_DB_PORT']
        username = os.environ['OPENSHIFT_MONGODB_DB_USERNAME']
        password = os.environ['OPENSHIFT_MONGODB_DB_PASSWORD']
        print('host = ' + host + ' port = ' + port)
        create(host, port, username, password)


